<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学期" prop="semId">
         <el-select v-model="queryParams.semId" filterable clearable placeholder="请选择学期">
           <el-option
             v-for="item in semsterList"
             :key="item.id"
             :label="item.title"
             :value="item.id"
             size="small">
           </el-option>
         </el-select>
       </el-form-item>
        <el-form-item label="专业" prop="specId">
          <el-select v-model="queryParams.specId" clearable placeholder="请选择专业" >
            <el-option
              v-for="item in specialtyList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="queryParams.classId" clearable filterable placeholder="请选择班级">
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
         <el-select v-model="queryParams.courseId" placeholder="请输入课程" clearable filterable>
           <el-option
             v-for="dict in courseList"
             :key="dict.id"
             :label="dict.title"
             :value="dict.id"
           />
         </el-select>
        </el-form-item>
      <el-form-item label="学生" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入学生"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分数" prop="scores">
        <el-col :span="11">
            <el-input
              v-model="queryParams.scoreMin"
              placeholder="请输入最低分"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-input
            v-model="queryParams.scoreMax"
            placeholder="请输入最高分"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="成绩级别" prop="level">
        <el-select v-model="queryParams.level" placeholder="请选择成绩级别" clearable size="small">
          <el-option
            v-for="dict in levelOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考核类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择考核类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['exam:examResult:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['exam:examResult:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['exam:examResult:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examResultList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学期" align="center" prop="semName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="学号" align="center" prop="code" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="课程" align="center" prop="courseName" />
      <el-table-column label="教师" align="center" prop="tname" />
      <el-table-column label="平时成绩" align="center" prop="result1"/>
      <el-table-column label="期中成绩" align="center" prop="result2"/>
      <el-table-column label="期末成绩" align="center" prop="result3"/>
      <el-table-column label="实操/实验成绩" align="center" prop="result4"/>
      <el-table-column label="总评成绩" align="center" prop="totalResult" />
      <el-table-column label="补考成绩" align="center" prop="makeupResult" :formatter="makeupFormat"/>
      <el-table-column label="清考成绩" align="center" prop="finalResult" :formatter="finalFormat"/>
      <el-table-column label="成绩级别" align="center" prop="level" :formatter="levelFormat" />
      <el-table-column label="考核类型" align="center" prop="type" :formatter="typeFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['exam:examResult:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-help"
            @click="handleView(scope.row)"
            v-hasPermi="['exam:examResult:edit']"
          >详细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['exam:examResult:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改成绩对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="view">
        <el-form-item label="学期" prop="semId">
          <el-select v-model="form.semId" filterable clearable placeholder="请选择学期" >
            <el-option
              v-for="item in semsterList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" clearable placeholder="请选择班级" @change="remoteStudent">
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生" prop="studentId">
          <el-select v-model="form.studentId" clearable placeholder="请选择学生" filterable>
            <el-option
              v-for="item in studentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
         <el-select v-model="form.courseId" placeholder="请输入课程" clearable filterable>
           <el-option
             v-for="dict in courseList"
             :key="dict.id"
             :label="dict.title"
             :value="dict.id"
           />
         </el-select>
        </el-form-item>
        <el-form-item label="教师" prop="teacherId">
         <el-select v-model="form.teacherId" placeholder="请输入课程" clearable filterable>
           <el-option
             v-for="dict in teacherList"
             :key="dict.userId"
             :label="dict.name"
             :value="dict.userId"
           />
         </el-select>
        </el-form-item>
        <el-form-item label="平时成绩" prop="result1">
          <el-input-number size="mini" :min="0" :max="100" :precision="1" v-model="form.result1" placeholder="请输入分数" />
        </el-form-item>
        <el-form-item label="期中成绩" prop="result2">
          <el-input-number size="mini" :min="0" :max="100" :precision="1" v-model="form.result2" placeholder="请输入分数" />
        </el-form-item>
        <el-form-item label="期末成绩" prop="result3">
          <el-input-number size="mini" :min="0" :max="100" :precision="1" v-model="form.result3" placeholder="请输入分数" />
        </el-form-item>
        <el-form-item label="实操/实验" prop="result4">
          <el-input-number size="mini" :min="0" :max="100" :precision="1" v-model="form.result4" placeholder="请输入分数" />
        </el-form-item>
        <el-form-item label="补考成绩" prop="makeupResult">
          <el-select v-model="form.makeupResult" placeholder="请选择成绩级别" >
            <el-option
              v-for="dict in levelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="清考成绩" prop="finalResult">
          <el-select v-model="form.finalResult" placeholder="请选择成绩级别" >
            <el-option
              v-for="dict in levelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成绩级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择成绩级别" >
            <el-option
              v-for="dict in levelOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考核类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择考核类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的成绩数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listExamResult, getExamResult, delExamResult, addExamResult, updateExamResult, exportExamResult, importTemplate } from "@/api/exam/examResult";
import { getToken } from "@/utils/auth";
import { selectSpecialty} from "@/api/base/specialty";
import { selectSemster} from "@/api/base/semster";
import { selectClazz } from "@/api/base/clazz";
import { selectCourse} from "@/api/base/course";
import { selectStudent} from "@/api/base/student";
import { selectTeacher} from "@/api/base/teacher";
export default {
  name: "ExamResult",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学期数据
      semsterList: [],
      // 专业表格数据
      specialtyList: [],
      // 班级表格数据
      classList: [],
      // 学生表格数据
      studentList: [],
      // 教师表格数据
      teacherList: [],
      // 课程数据
      courseList: [],
      // 成绩表格数据
      examResultList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 成绩级别字典
      levelOptions: [],
      // 考核类型字典
      typeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        semId: null,
        classId: null,
        studentId: null,
        courseId: null,
        result1: null,
        result2: null,
        result3: null,
        result4: null,
        result5: null,
        makeupResult: null,
        finalResult: null,
        totalResult: null,
        level: null,
        type: null,
        status: null
      },
      view: false,
      // 表单参数
      form: {},
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/exam/examResult/importData"
      },
      resultName:[],
      // 表单校验
      rules: {
        semId: [
          { required: true, message: "学期不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "班级不能为空", trigger: "blur" }
        ],
        studentId: [
          { required: true, message: "课程不能为空", trigger: "blur" }
        ],
        courseId: [
          { required: true, message: "课程不能为空", trigger: "blur" }
        ],
        teacherId: [
          { required: true, message: "教师不能为空", trigger: "blur" }
        ],
        level: [
          { required: true, message: "成绩级别不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("result_level").then(response => {
      this.levelOptions = response.data;
    });
    this.getDicts("exam_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getConfigKey("edu.result.name").then(response => {
      var names = response.msg.split(" ");
      for(var i=0;i<names.length; i++){
        if(names[i] == null || names[i] == '') continue;
        var kv = names[i].split('=');
        this.resultName.push({field:'result'+kv[0], title:kv[1]})
      }
    });
    selectClazz().then(response => {
      this.classList = response.rows;
      this.total = response.total;
      this.loading = false;
    });
    selectSemster({'status':1}).then(response => {
      this.semsterList = response.rows;
    });
    selectCourse().then(response => {
      this.courseList = response.rows;
      this.total = response.total;
    });
    selectTeacher({'status':1}).then(response => {
        this.teacherList = response.rows;
        this.total = response.total;
      });
  },
  methods: {
    /** 查询成绩列表 */
    getList() {
      this.loading = true;
      listExamResult(this.queryParams).then(response => {
        this.examResultList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 成绩级别字典翻译
    levelFormat(row, column) {
      return this.selectDictLabel(this.levelOptions, row.level);
    },
    makeupFormat(row, column) {
      return this.selectDictLabel(this.levelOptions, row.makeupResult);
    },
    finalFormat(row, column) {
      return this.selectDictLabel(this.levelOptions, row.finalResult);
    },
    // 考核类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    remoteStudent() {
      this.loading = true;
      selectStudent({classId:this.form.classId}).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        semId: null,
        classId: null,
        studentId: null,
        courseId: null,
        result1: null,
        result2: null,
        result3: null,
        result4: null,
        result5: null,
        makeupResult: null,
        finalResult: null,
        totalResult: null,
        level: null,
        type: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.view = false;
      this.title = "添加成绩";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getExamResult(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.remoteStudent();
        this.view = false;
        this.title = "修改成绩";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getExamResult(id).then(response => {
        this.form = response.data;
        this.remoteStudent();
        this.open = true;
        this.view = true;
        this.title = "修改成绩";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateExamResult(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addExamResult(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除选中的成绩' + ids + '数据?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delExamResult(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有成绩数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportExamResult(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "成绩导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
